﻿using System;
using ProjectAutumn.Graphics;
using Tao.Sdl;

namespace ProjectAutumn.GraphicsDevice.SDL
{
    class SDLTexture : Texture
    {
        private readonly IntPtr mainSurface;
        private readonly unsafe Sdl.SDL_Surface* surface;
        public IntPtr Handle
        {
            get { return mainSurface; }
        }
        public unsafe SDLTexture(string file)
        {
            mainSurface = SdlImage.IMG_Load(file);
            if(mainSurface == IntPtr.Zero)
                throw new Exception(Sdl.SDL_GetError());
            surface = (Sdl.SDL_Surface*)mainSurface.ToPointer();
        }
        public unsafe SDLTexture(int width, int height)
        {
            mainSurface = Sdl.SDL_CreateRGBSurface(Sdl.SDL_HWSURFACE | Sdl.SDL_SRCALPHA, width, height, 32, 0, 0, 0, 0);
            if (mainSurface == IntPtr.Zero)
                throw new Exception(Sdl.SDL_GetError());
            surface = (Sdl.SDL_Surface*)mainSurface.ToPointer();
        }
        public override void Dispose()
        {
            Sdl.SDL_FreeSurface(mainSurface);
        }
        public override void SetData(Color[] color, int start, int length)
        {
            for(int i = start; i < length; i++)
            {
                Sdl.SDL_Rect rect = new Sdl.SDL_Rect();
                rect.w = rect.h = 1;
                rect.x = (short)(i % Width);
                rect.y = (short)(i / Width);
                Sdl.SDL_FillRect(mainSurface, ref rect, color[i].PackedValue);
            }
        }
        public override unsafe int Width
        {
            get { return surface->w; }
        }
        public override unsafe int Height
        {
            get { return surface->h; }
        }
    }
}
